﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Threading;

namespace Htinns.GatewayConsole.Extentions
{
	public class ResubmitAttribute: ActionFilterAttribute
	{
		private static System.Collections.Concurrent.ConcurrentQueue<string> _transactions = new System.Collections.Concurrent.ConcurrentQueue<string>();

		private static System.Collections.Concurrent.ConcurrentDictionary<string, string> _transactions2 = new System.Collections.Concurrent.ConcurrentDictionary<string, string>();

		public override void OnActionExecuting(ActionExecutingContext filterContext)
		{			

			string transactionId = filterContext.HttpContext.Request.Params["transactionId"];

			if (_transactions2.ContainsKey(transactionId))
			{
				filterContext.Result = new RedirectResult("/Home/Resubmit");
			}
			else {
				_transactions.Enqueue(transactionId);

				while (!_transactions2.TryAdd(transactionId, transactionId))
				{
				}
			}

			int max = 200000;

			//处理100 000并发
			if (_transactions.Count > max)
			{
				string firstValue;

				while (!_transactions.TryDequeue(out firstValue))
				{
					if (_transactions.Count < max)
					{
						return;
					}
				}

				string value;

				if (firstValue != null)
				{
					while (!_transactions2.TryRemove(firstValue, out value))
					{
					}
				}
			}
		}		
					
	}
}